package com.example.demo.service.serviceImp;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImp implements UserService {
    @Autowired
    private UserMapper mapper;

    /**
     * 注册
     * @param user
     * @return
     */
    public User addUser(User user) {

        User tmp =  mapper.selectByUid(user.getUid());
        if (tmp == null) {
            String newPwd = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex
                    (user.getPwd().getBytes()).getBytes());
            user.setPwd(newPwd);
            user.setCreatedate(new Date());
            mapper.inserts(user);
        } else return new User(null);
        return user;
    }

    /**
     * 登录
     * @param uid
     * @param password
     * @return
     */
    public User login(String uid,String password){
        String newPwd = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex
                (password.getBytes()).getBytes());
        User result = mapper.selectByUidPwd(uid,newPwd);
        return result;
    }

    /**
     * 查询
     * @param page
     * @param limit
     * @param example
     * @return
     */
    public List<User> searchByExample(int page,int limit,User example) {
        int begin = limit * (page-1);
        List<User> result = mapper.selectByExample(begin,limit,example);
        return result;

    }

    /**
     * 查询总数
     * @param example
     * @return
     */

    public int searchByExampleCount(User example){

        return mapper.selectByExampleCount(example);
    }

    /**
     * 更新用户信息
     * @param example
     * @return
     */
    public int updateByPrimaryKey(User example){
        User tmp =  mapper.selectByUid(example.getUid());
        if (tmp != null) {
            String newPwd = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(example.getPwd().getBytes()).getBytes());
            example.setPwd(newPwd);
            example.setUpdatedate(new Date());
            return mapper.updateByPrimaryKeySelective(example);
        }
        return -1;
    }

    /**
     * 删除用户信息
     * @param id
     * @return
     */

    public int deleteByPrimaryKey(int id){

        return mapper.deleteByPrimaryKey(id);
    }
}
